package com.zhuiYun.project.config.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zhuiYun.project.api.sysUser.entiy.SysUser;
import com.zhuiYun.project.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @ClassName JwtUtils
 * @Description JWT 工具类
 * @Author zcy
 * @Date 2023/3/28 8:31
 **/
public class JWTUtils {


    /**
     * 校验是否正确
     *
     * @param token
     * @param
     * @return
     */
    public static boolean verify(String token) {
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(JWTConfig.secretKey);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            // 效验TOKEN
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }


    /**
     * 从Token中解密数据
     * @param token
     * @return
     */
    public static String getInfo(String token, String name) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(name).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }


    /**
     * 生成JWT Token字符串
     * @param sysUser
     * @return
     */
    public static String createAccessToken(SysUser sysUser) {
        Date date = new Date(System.currentTimeMillis() + JWTConfig.expiration);
        Algorithm algorithm = Algorithm.HMAC256(JWTConfig.secretKey);
        // 附带username信息
        return JWT.create()
                .withClaim("username", sysUser.getUserName())
                .withClaim("loginName", sysUser.getLoginName())
                //.withExpiresAt(date) // 暂不指定过期时间 redis中设置
                .sign(algorithm);
    }

    /**
     * 将前端传过来的token中的tokenPrefix去掉
     * @param request
     * @return
     */
    public static String getToken(HttpServletRequest request) {
        String tokenHeader = "";
        // 验证token 并截取token
        if(checkRequestToken(request)){
            tokenHeader = request.getHeader(JWTConfig.tokenHeader).replace(JWTConfig.tokenPrefix, "");
        }
        return tokenHeader;
    }

    /**
     * 验证请求中的token是否格式正确
     * @param request
     * @return
     */
    public static boolean checkRequestToken(HttpServletRequest request) {
        String tokenHeader = request.getHeader(JWTConfig.tokenHeader);
        if (ObjectUtils.isNotEmpty(tokenHeader) && tokenHeader.startsWith(JWTConfig.tokenPrefix)) {
            return true;
        }
        return false;
    }
}
